package com.gupaoedu.vip.orm.test;

import com.gupaoedu.vip.orm.demo.entity.Member;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: JLL
 * @Date: 2019/5/26 9:57
 */
public class JdbcTestGuocheng1 {


    public static void main(String[] args) {
        Member condition = new Member();
        condition.setName("Tom");
        condition.setAge(19);
        List<?> result =  select(condition);
        System.out.println(Arrays.toString(result.toArray()));

    }

    /**
     * 1、开始方法里不传参数，直接select *
     */
    private static List<?> select(Object condition) {
        List<Member> result = new ArrayList<>();


        Class<?> entityClass = condition.getClass();


        Connection con = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        try{
            //1、加载驱动类
            Class.forName("com.mysql.jdbc.Driver");
            //2、建立连接
            con = DriverManager.getConnection("jdbc:mysql://192.168.150.130:3306/gp-vip-spring-db-demo?characterEncoding=UTF-8&rewriteBatchedStatements=true","root","123456");

            //3.创建语集
            String sql = "select * from t_member";
            pstm = con.prepareStatement(sql);

            Field[] fields  =  entityClass.getDeclaredFields();


            //4、执语句集
            rs = pstm.executeQuery();
            while(rs.next()){


                //实体类，属性名 ，对应数据库表的字段名
                //可以通过反射拿到实体类所有的字段。  （前提是类名和属性名要保持一致，这里暂且认为是一致的）



                //1、实际中，这段代码肯定不会这么写
                Member m = new Member();
                m.setId(rs.getLong("id"));
                m.setName(rs.getString("name"));
                m.setAddr(rs.getString("addr"));
                m.setAge(rs.getInt("age"));

                result.add(m);
            }


        } catch (Exception e){
            e.printStackTrace();
        }
        //6、关闭结果集、关闭语句集、关闭连接
        finally {
            try {
                rs.close();
                pstm.close();
                con.close();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return result;
    }








}
